<template>
  <view>
      <u-navbar
          :background="{ backgroundColor:'#9CE0FF'}"
          :border-bottom="false"
          title="保养详情"
          title-color="#000"
          title-size="37"
      />
    <view id="container" :style="{minHeight:`calc(100vh - ${top}px)`}" class="flex flex-column justify-between">
      <view class="mt-20">
        <sub-title title="保养概况"></sub-title>
        <view class="flex space-evenly p-tb-20 pl-20">
          <view
              class="flex1 flex flex-column align-center justify-center color-fff bg-FF9900 h-200 mr-20 br-10"
          >
            <text class="fz-40 lh-56 mb-10">{{ showData(unDone) }}</text>
            <text class="fz-24 lh-33">未保养</text>
          </view>
          <view
              class="flex1 flex flex-column align-center justify-center color-fff bg-19BE6B h-200 mr-20 br-10"
          >
            <text class="fz-40 lh-56 mb-10">{{ showData(done) }}</text>
            <text class="fz-24 lh-33">已保养</text>
          </view>

        </view>
        <view class="p-lr-40">
          <view class="color-888888 fz-30 lh-42 w-full mb-20">
            <text>保养开始时间</text>
            <text class="f-r">{{ workOrderInfo.startTime || '-' }}</text>
          </view>
          <view class="color-888888 fz-30 lh-42 w-full mb-20">
            <text>保养结束时间</text>
            <text class="f-r">{{ workOrderInfo.endTime || '-'}}</text>
          </view>
          <view class="color-888888 fz-30 lh-42 w-full mb-20 flex">
            <text class="w-200">保养工程师</text>
            <view class="flex1 text-right">
              <text>{{ workOrderInfo.mroUser || '-' }}</text>
            </view>
          </view>
          <view class="color-888888 fz-30 lh-42 w-full mb-20 flex align-center justify-between" v-if="orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[5]">
            <text>签名情况</text>
            <view class="flex align-center">
              <text class="f-r fz-30">已签名</text>
            </view>
          </view>
          <view class="fz-30 lh-42 w-full mb-20 flex align-center justify-end color-19BE6B f-r" v-if="orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[5]">
            <view class="flex align-center mr-30" @tap="showSign">
              <image class="h-26 w-35 mr-10" src="@/static/images/equipment/eyeV2.png"></image><text>{{ signType[0].label }}</text>
            </view>
            <view class="flex align-center" @tap="showSignPaper">
              <image class="h-26 w-35 mr-10" src="@/static/images/equipment/eyeV2.png"></image><text>{{ signType[1].label }}</text>
            </view>
          </view>
        </view>
        <sub-title title="保养详情"></sub-title>
        <view class="p-lr-20 pb-35">
          <u-collapse :accordion="false">
            <u-collapse-item
                v-for="(roomListItem, roomListItemIndex) in roomList"
                :key="roomListItemIndex"
            >
              <view slot="title" class="flex justify-between align-center w-full fz-34 pl-20 pr-15 ">
                <view class="flex justify-center bg-19BE6B br-32 min-w-200 max-w-460 p-lr-22 p-tb-8">
                  <view class="lh-48 color-fff font-bold text-ellipsis-2">
                    <text>{{ roomListItem.roomName }}</text>
                  </view>
                </view>
                <text
                    class="f-r"
                    :class="[ !roomListItem.doneNum ? 'color-2D8CF0':roomListItem.isAllDone ?'color-19BE6B':'color-FF6262']"
                >
                  {{showNum(roomListItem.doneNum ,roomListItem.totalNum)}}
                </text>
              </view>
              <view>
                <view class="border-top-CCCCCC pt-15">
                  <view
                      v-for="(equipmentListItem, equipmentListItemIndex) in roomListItem.equipmentList"
                      :key="equipmentListItemIndex"
                      @tap="toCheckItemDetail(equipmentListItem)"
                      class="bg-E9F8FF br-10 mb-20"
                  >
                    <view class="flex justify-between p-10">
                      <view class="flex flex1 oh">
                        <view class="br-round h-18 w-18 bg-9CE0FF mr-10 mt-15"></view>
                        <text class="flex1 fz-32 lh-45 color-333333">{{equipmentListItem.deviceName}}</text>
                      </view>
                      <image
                          class="h-28 w-14 mt-8"
                          src="@/static/images/common/toPath.png"
                      ></image>
                    </view>
                    <view
                        v-for="(standardListItem, standardListIndex) in equipmentListItem.projectList"
                        :key="standardListIndex"
                        class="fz-26 p-lr-20 pb-20 flex justify-between align-center"
                    >
                      <text class="block flex2 mr-20 break-all">{{ standardListItem.projectName || '-'}}</text>
                      <view class="flex1 flex justify-end">
                        <text class="color-19BE6B">{{standardListItem.result || '-'}}</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </u-collapse-item>
          </u-collapse>
        </view>
      </view>
      <view v-if="orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[0]" class="flex align-center justify-center h-150 border-top-EEEEEE sticky bottom0 bg-fff">
        <view class="h-80 w-250 br-10 bg-19BE6B color-fff fz-30 lh-80 text-center" @tap="toChooseWorker">
          <text>派单</text>
        </view>
      </view>
      <view
          v-else-if="(orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[1] || orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[3])"
          class="flex align-center justify-center h-150 border-top-EEEEEE sticky bottom0 bg-fff">
        <view class="h-80 w-250 br-10 bg-19BE6B color-fff fz-30 lh-80 text-center" @tap="toChooseWorker">
          <text>转派</text>
        </view>
      </view>
      <view v-else-if="orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[4]"
            class="flex align-center justify-center h-150 border-top-EEEEEE sticky bottom0 bg-fff">
        <view class="w-250 h-80 lh-80 br-10 fz-30 text-center mr-50 color-fff bg-2DB7F5" @tap="share">
          <text>分享</text>
        </view>
        <view class="h-80 w-250 br-10 bg-19BE6B color-fff fz-30 lh-80 text-center" @tap="paperVersion">
          <text>录入纸质版</text>
        </view>
      </view>
      <view v-else-if="(orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[2] || orderStatus === MAINTENANCE_ORDER_STATUS_VALUE[6])" class="flex align-center justify-center h-150 border-top-EEEEEE sticky bottom0 bg-fff">
        <view class="h-80 w-250 br-10 border-19BE6B color-19BE6B fz-30 lh-80 text-center" @tap="isTimePickerShow = true">
          <text>延长工单</text>
        </view>
      </view>
    </view>

    <u-picker
        :defaultTime="defaultTime"
        v-model="isTimePickerShow"
        :params="params"
        mode="time"
        safe-area-inset-bottom
        :title="title"
        @confirm="confirm"
        @cancel="cancel"
        control
    >
    </u-picker>
    <!--图片上传中模态框-->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>

    <!--图片加水印画板-->
    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="`mycanvas`" >
    </canvas>

  </view>
</template>

<script>
import SubTitle from "@/components/SubTitle/SubTitle";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import {workOrderInfo, querySign, delayEndDate} from "@/api/maintenance/task";
import {listWorkOrderDevice} from "@/api/maintenance/workOrderDevice";
import { signByPaper } from '@/api/maintenance/sign'
import config from '@/config'
import dayjs from '@/libs/dayjs.min.js'
import uploadMaskImg from "@/mixins/uploadMaskImg";
import { DIC , MAINTENANCE_ORDER_STATUS } from '@/utils/dict'

export default {
  name: "maintenanceOrderDetail",
  components: {SubTitle},
  mixins: [getNavBarHeight,uploadMaskImg],
  onLoad(options) {
    this.workOrderId = options.workOrderId
  },
  onShow(){
    this.doQuery()
  },
  data() {
    return {
      workOrderInfo: {},
      workOrderId: '',
      unDone: 0,
      done: 0,
      roomList: [],
      //设备原始列表
      deviceListoriginalData: [],
      isUploading: false,
      defaultTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      isTimePickerShow:false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      title: '请选择延长日期',
      signData:[]
    }
  },
  computed:{
    MAINTENANCE_ORDER_STATUS_VALUE(){
      return MAINTENANCE_ORDER_STATUS.map(el=>el.value)
    },
    signType(){ return DIC.signType },
    orderStatus(){
      return this.workOrderInfo.status
    },
  },
  watch: {
    deviceListoriginalData(newValue) {
      if(!newValue) return
      //生成树结构
      this.roomList = newValue.reduce((pre, next) => {
        let temp = pre.find(item => {
          return item.roomId === next.roomId
        })
        if (temp) temp.equipmentList.push(next);
        else pre.push({equipmentList: [next],roomId: next.roomId, roomName: next.roomName});
        return pre
      }, [])
      //计算每个房间的总标准数和已完成标准数
      this.roomList.forEach(roomListItem => {
        roomListItem.totalNum = roomListItem.equipmentList.reduce((pre,next) => {
          return pre + next.projectList.length
        },0)
        roomListItem.doneNum = roomListItem.equipmentList.reduce((pre,next) => {
          let temp = next.projectList.reduce((standardListPre,standardListnext) => {
            if(standardListnext.result){
              standardListPre++
            }
            return standardListPre
          },0)
          return pre + temp
        },0)
        roomListItem.isAllDone = roomListItem.totalNum === roomListItem.doneNum
      })
      this.done = 0
      this.unDone = 0
      //统计未巡检.已巡检.异常数
      newValue.forEach(item => {
        item.projectList.forEach(standardListItem => {
          if(standardListItem.value || standardListItem.value == 0 || standardListItem.result ){
            this.done++
          }else{
            this.unDone ++
          }
        })
      })
    }
  },
  methods: {
    share(){
      uni.share({
        provider: 'weixin',
        scene: "WXSceneSession",
        type: 5,
        imageUrl: '../../static/images/common/sharePic.png',
        title: `保养工单-${this.workOrderInfo.workOrderName}`,
        miniProgram: {
          id: 'gh_84e59957fd69',
          path: `pages/maintenance/maintenance-order-detail-byShare?workOrderId=${this.workOrderId}&hospitalId=${this.workOrderInfo.hospitalId}&departmentId=${this.workOrderInfo.departmentId}`,
          type: config.miniProgramType,
          webUrl: 'http://purification.jiuzhangzhineng.com/'
        },
        fail: err => {
          uni.showToast({
            title: err,
            icon : 'none'
          });
        }
      });
    },
    confirm(e){
      const now = dayjs()
      const endDate = dayjs(`${e.year}-${e.month}-${e.day}`)
      let delayDate = ''
      if(endDate.isBefore(now)){
        delayDate = now.format("YYYY-MM-DD")
      }else{
        delayDate = endDate.format("YYYY-MM-DD")
      }
      delayEndDate({workOrderId: this.workOrderId, delayEndDate:delayDate}).then(res => {
        if(res.code===200){
          uni.showToast({
            title: '延长工单日期成功！',
            duration: 2000,
            icon:'none'
          });
          setTimeout(()=> {
            uni.navigateBack({
              delta: 1
            })
          },1900)
        }
      })
    },
    cancel(){
      this.isTimePickerShow = false
    },
    doQuery() {
      workOrderInfo(this.workOrderId).then(res => {
        this.workOrderInfo = res.data || {}
      })
      listWorkOrderDevice({workOrderId: this.workOrderId}).then(res => {
        res.data.forEach(item => {
          item.projectList.forEach(standardListItem => {
            if(standardListItem.type === '1' && standardListItem.result){
              standardListItem.resultArray = standardListItem.result.split(',')
            }
          })
        })
        this.deviceListoriginalData = res.data
      })
      querySign(this.workOrderId).then(res => {
        this.signData = res.data || []
      })
    },
    toSign() {
      this.$tab.navigateTo('/pages/sign/sign?workOrderId=' + this.workOrderId)
    },
    toChooseWorker(){
      this.$tab.navigateTo('/pages/maintenance/choose-worker?workOrderId=' + this.workOrderInfo.workOrderId + '&hospitalId=' + this.workOrderInfo.hospitalId + '&byBatch=0')
    },
    showData(data) {
      return data > 99 ? "99+" : data;
    },
    showNum(doneNum ,totalNum){
      if(!doneNum){
        return '待保养'
      }
      return doneNum + '/' + totalNum
    },
    paperVersion() {
      this.uploadMaskImg()
    },
    //水印内容
    maskContent(ctx, image){
      ctx.strokeText(this.workOrderInfo.workOrderName || '-',image.width * 0.092,image.width * 0.18);
      ctx.fillText(this.workOrderInfo.workOrderName || '-', image.width * 0.092, image.width * 0.18)

      ctx.strokeText(this.$store.getters.staffName || '-',image.width * 0.092,image.width * 0.23);
      ctx.fillText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.23)

      ctx.strokeText(dayjs().format('YYYY-MM-DD HH:mm:ss'),image.width * 0.092,image.width * 0.28);
      ctx.fillText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.28)
    },

    //水印图片上传成功后回调函数
    uploadSuccessCallback(data) {
      signByPaper({ ossId: `${data.data.ossId}`, workOrderId: this.workOrderInfo.workOrderId }).then(res => {
        if(res.code === 200){
          uni.showToast({
            'title': '上传成功'
          })
          this.doQuery()
        }
        else{
          uni.showToast({
            'title': '上传失败'
          })
        }
      })
    },

    toCheckItemDetail(equipmentItemInfo) {
      this.$tab.navigateTo('/pages/maintenance/check-item-detail?deviceId=' + equipmentItemInfo.deviceId + '&workOrderId=' + this.workOrderInfo.workOrderId + '&workOrderDeviceId=' +  equipmentItemInfo.workOrderDeviceId)
    },

    //获取巡检标准的值
    standardListItemValue(item) {
      if (item.type == 0 || item.type == 1) {
        return  item.result ? item.result : '-'
      }else{
        return  item.value || item.value==0 ? parseFloat(item.value) + (item.unit ? item.unit : '') : '-'
      }
    },
    //查看签名情况
    showSign(){
      this.getSignUrl(this.signType[0])
    },
    showSignPaper(){
      this.getSignUrl(this.signType[1])
    },
    getSignUrl(signItem){
      const signData = this.signData.find(el=>el.signType === signItem.value) || null
      if(signData){
        uni.previewImage({
          urls: [signData.url],
          indicator: "none"
        });
      }else{
        uni.showToast({
          title: '暂无' + signItem.label,
          icon : 'none'
        });
      }
    }
  },
  options: {styleIsolation: "shared"},
}
</script>

<style lang="scss">
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
/deep/ .u-arrow-down-icon {
  margin-right: 0 !important;
  margin-left: 11 rpx !important;
}
.resultArrayItem > text:not(:last-child):after{
  content: ',';
}
</style>
